//
//  HWyouxixiangqinglimiandepinglunView.m
//  HWanGame
//
//  Created by 陈道斌 on 2020/12/1.
//  Copyright © 2020 Chendaobin. All rights reserved.
//

#import "HWyouxixiangqinglimiandepinglunView.h"

#import "LFOpinionView.h"
#define MAX_LIMIT_NUMS 120

@interface HWyouxixiangqinglimiandepinglunView()<UITextViewDelegate>
@property(strong,nonatomic) UIView *grayView;
//@property(strong,nonatomic) UIView *whiteView;
@property(strong,nonatomic) UIView *fenxiangView;

@property(strong,nonatomic)UIView *pingfenView;
@property(assign,nonatomic) int xuanzhong;
@property (nonatomic, strong) LFOpinionView *textView;
@property(strong,nonatomic) UIButton *fasongButon;
@property(strong,nonatomic) UILabel *rulesLabel;


@end


@implementation HWyouxixiangqinglimiandepinglunView


- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
          // 添加灰色背景
          [self setupUI];
        
    }
    
    
    return  self;
    
    
    
    
    
}




//
- (void)setupUI {
    
 
    

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake( 20,0, 200, 55)];
             
            //   label.autoresizingMask = UIViewAutoresizingFlexibleWidth;

              label.textColor = QCmorenzitiHeiSe;
              // label.shadowColor = [UIColor colorWithWhite:.9f alpha:1.0f];
              //label.shadowOffset = CGSizeMake(0.0f, 1.0f);
              label.backgroundColor = [UIColor clearColor];
              //        label.textAlignment = UITextAlignmentLeft;
              label.text = @"全部评论";
            label.text = [HWjianzhiduiObject keylocalization:@"全部评论"];
              [self  addSubview:label];
       
              UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
              button1.frame = CGRectMake(kScreenW-36-10, 0, 36, 55);
             //  [button1 setBackgroundImage:[UIImage imageNamed:@"shutdownGuanbi"] forState:UIControlStateNormal];
            //  button1.backgroundColor = [UIColor redColor];
              [button1 addTarget:self action:@selector(buttonTouxiangTap) forControlEvents:UIControlEventTouchUpInside];
              [button1 setImage:[UIImage imageNamed:@"shutdownGuanbi"] forState:UIControlStateNormal];
       
              [self addSubview:button1];
    
    
         
    
                 
             
           UIView  *pingfenView = [[UIView alloc]initWithFrame:CGRectMake(0, 55, kScreenW, 20)];
           pingfenView.backgroundColor = [UIColor whiteColor];
           self.pingfenView  = pingfenView;
           pingfenView.hidden = YES;
           [self addSubview:pingfenView];
    
    
    
                UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(20,0, 35, 20)];
               label1.font = [UIFont systemFontOfSize:14];
    
              //   label.autoresizingMask = UIViewAutoresizingFlexibleWidth;

                label1.textColor = RGB(136, 136, 136);
                // label.shadowColor = [UIColor colorWithWhite:.9f alpha:1.0f];
                //label.shadowOffset = CGSizeMake(0.0f, 1.0f);
                label1.backgroundColor = [UIColor whiteColor];
                //        label.textAlignment = UITextAlignmentLeft;
                label1.text = @"评分";
                label1.text = [HWjianzhiduiObject keylocalization:@"评分"];
    
                [pingfenView  addSubview:label1];
    
    
         for (int i =0; i < 5 ; i++) {
         
              UIButton   *buton = [UIButton buttonWithType:UIButtonTypeCustom];
              buton.frame = CGRectMake(20+35+i*24, 2, 24, 15);
              [buton setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
              //  self.recommendedBut.backgroundColor = [UIColor redColor];
             [buton setBackgroundImage:[UIImage imageNamed:@"pinglunweixuanzhon_ico"] forState:UIControlStateNormal];
              [buton setBackgroundImage:[UIImage imageNamed:@"quanxing_ico"] forState:UIControlStateSelected];
        
              [buton addTarget:self action:@selector(tuijianTap:) forControlEvents:UIControlEventTouchUpInside];
             buton.tag = i+100;
             
             [pingfenView addSubview:buton];
             
             
         }
    
    
    self.xuanzhong = 0;
    
    
    
        
    
    
    
         _textView = [[LFOpinionView alloc] init];
         _textView.alwaysBounceVertical = YES;
         _textView.delegate = self;
    //     _textView.x = 10;
    //     _textView.y = 0;
         _textView.frame = CGRectMake(30, pingfenView.bottom+20, kScreenW- 60, 110);
         _textView.backgroundColor = [UIColor whiteColor];
          _textView.backgroundColor = RGB(245, 245, 245);
         _textView.textColor = RGB(51, 51, 51);
         _textView.placeholder = @"请输入评论内容";
    
         _textView.placeholder = [HWjianzhiduiObject keylocalization:@"请输入评论内容"];
    
         _textView.font = [UIFont systemFontOfSize:14];
        _textView.layer.cornerRadius =10 ;
         _textView.layer.masksToBounds = YES;
         [self addSubview:_textView];
    
    
    
    NSString *fason =  [HWjianzhiduiObject keylocalization:@"发送"];
    
    self.fasongButon  = [UIButton setButtonWithFrame:CGRectMake(20, self.textView.bottom+20,  kScreenW -40, 44) Title:fason Image:nil Font:15 Color:RGB(255, 255, 255) Target:self Selector:@selector(fasongButtap)];
      self.fasongButon.backgroundColor = [UIColor  bm_colorGradientChangeWithSizeView:  self.fasongButon];
      self.fasongButon.layer.cornerRadius = 22;
      self.fasongButon.layer.masksToBounds = YES;
      [self addSubview:self.fasongButon];
    
    
    
    
    
       UILabel *netLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, self.fasongButon.bottom+10, kScreenW-40, 140)];
     netLabel.textColor  = RGB(136, 136, 136);
     netLabel.text = @"评论规则\n1.点评内容必须原创，严禁抄袭;\n2.真实表达，文明吐槽，有理有据;\n3.理性表达个人意见，不偏激,不偏见;\n4.在事实依据的基础上对游戏进行点评，客观公正;\n5.观点独特有趣，可读性强;\n6.逻辑清晰，语言简练";
    
    netLabel.text = [HWjianzhiduiObject keylocalization:@"评论规则\n1.点评内容必须原创，严禁抄袭;\n2.真实表达，文明吐槽，有理有据;\n3.理性表达个人意见，不偏激,不偏见;\n4.在事实依据的基础上对游戏进行点评，客观公正;\n5.观点独特有趣，可读性强;\n6.逻辑清晰，语言简练"];
    
     netLabel.font = [UIFont systemFontOfSize:12];
     netLabel.numberOfLines = 0;
     self.rulesLabel = netLabel;
     
     [self addSubview:netLabel];
    
    
    
    
    
  

}


- (void)tuijianTap:(UIButton *)sender {
    
    if (sender.tag == 100) {
        
        
        if (self.xuanzhong == 0  || self.xuanzhong  ==  1 ) {
            
            
            
           if (sender.selected == NO) {
                   
                   sender.selected = YES;
                   self.xuanzhong = 1;
                   
                   
               }else {
                   
                     sender.selected = NO;
                    self.xuanzhong = 0;
                   
                   
               }
            
            return ;
            
        }  else {
            
            return ;
            
            
            
        }
        
        
     
        
    } else if (sender.tag == (1+100)) {
        
           
       
        
        

         
          if (self.xuanzhong == 1  || self.xuanzhong  ==  2 ) {
              
              
                    if (sender.selected == NO) {
                           
                           sender.selected = YES;
                            self.xuanzhong = 2;
                           
                       }else {
                           
                             sender.selected = NO;
                              self.xuanzhong = 1;
                           
                       }
                
              
              
                   return;
          } else {
              
               return;
              
          }
        
        
        
        
        
           
//               if (sender.selected == NO) {
//
//                   sender.selected = YES;
//                    self.xuanzhong = 2;
//
//               }else {
//
//                     sender.selected = NO;
//                      self.xuanzhong = 1;
//
//               }
        
        
        
    } else if (sender.tag == (2+100)) {
        
        
        
        
        
        
        
        
        
        if (self.xuanzhong == 2  || self.xuanzhong  ==  3 ) {
                    
                    
            if (sender.selected == NO) {
                                 
                 sender.selected = YES;
                  self.xuanzhong = 3;
                                 
            }else {
                                 
                    sender.selected = NO;
                    self.xuanzhong = 2;
                                 
             }
                      
                    
            return;
                        
         } else {
                    
            return;
                    
        }
              
        
        
    } else if (sender.tag == (3+100)) {
        
        
           if (self.xuanzhong == 3  || self.xuanzhong  ==  4 ) {
                          
                          
                  if (sender.selected == NO) {
                                       
                       sender.selected = YES;
                        self.xuanzhong = 4;
                                       
                  }else {
                                       
                          sender.selected = NO;
                          self.xuanzhong = 3;
                                       
                   }
                            
                          
                  return;
                              
               } else {
                          
                  return;
                          
              }
                
        
        
        
        
        
        
        
        
        
    } else if (sender.tag == (4+100)) {
        
        
        if (self.xuanzhong == 4  || self.xuanzhong  ==  5 ) {
                               
                               
                       if (sender.selected == NO) {
                                            
                            sender.selected = YES;
                             self.xuanzhong = 5;
                                            
                       }else {
                                            
                               sender.selected = NO;
                               self.xuanzhong = 4;
                                            
                        }
                                 
                               
                      return;
                                   
                    } else {
                               
                       return;
                               
                   }
                     
        
        
        
        
        
        
        
    }
    
    
    
    
    
    
}






-(void)buttonTouxiangTap {
    
    
    
    [[self superview]  removeFromSuperview];
    
}



- (void)relayoutTheChildControls {
//    // self.whiteView.backgroundColor = [UIColor redColor];
//    self.whiteView.frame = CGRectMake(0, self.whibackvieY, kScreenW, 120);
//    self.grayView.frame = CGRectMake(0, self.whibackvieY+120, kScreenW, kScreenH-self.whibackvieY-118+10);
//

    
}





- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
}


//第一个方法用于限制输入，第二个方法用于动态计算剩余字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range

 replacementText:(NSString *)text

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //获取高亮部分内容

    //NSString * selectedtext = [textView textInRange:selectedRange];

    

    //如果有高亮且当前字数开始位置小于最大限制时允许输入

    if (selectedRange && pos) {

        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];

        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];

        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);

        

        if (offsetRange.location < MAX_LIMIT_NUMS) {

            return YES;

        }

        else

        {
            [MBProgressHUD showError:@"最多只能输入120个字符"];

            return NO;

        }

    }

    

    

    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];

    

    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;

    

    if (caninputlen >= 0)

    {

        return YES;

    }

    else

    {

        NSInteger len = text.length + caninputlen;

        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错

        NSRange rg = {0,MAX(len,0)};

        

        if (rg.length > 0)

        {

            NSString *s = @"";

            //判断是否只普通的字符或asc码(对于中文和表情返回NO)

            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];

            if (asc) {

                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错

            }

            else

            {

                __block NSInteger idx = 0;

                __block NSString  *trimString = @"";//截取出的字串

                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个

                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])

                                         options:NSStringEnumerationByComposedCharacterSequences

                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {

                                          

                                          if (idx >= rg.length) {

                                              *stop = YES; //取出所需要就break，提高效率

                                              return ;

                                          }

                                          

                                          trimString = [trimString stringByAppendingString:substring];

                                          

                                          idx++;

                                      }];

                

                s = trimString;

            }

            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)

            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];

            //既然是超出部分截取了，哪一定是最大限制了。

         //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%d个字",0];

        }
        
        
         [MBProgressHUD showError:@"最多只能输入120个字符"];

        return NO;

    }

    

}

 

- (void)textViewDidChange:(UITextView *)textView

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    

    //如果在变化中是高亮部分在变，就不要计算字符了

    if (selectedRange && pos) {

        return;

    }

    

    NSString  *nsTextContent = textView.text;

    NSInteger existTextNum = nsTextContent.length;

    

    if (existTextNum > MAX_LIMIT_NUMS)

    {

        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)

        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];

        

        [textView setText:s];

    }

    

    //不让显示负数

 //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%ld个字",MAX(0,MAX_LIMIT_NUMS - existTextNum)];

}





- (void)fasongButtap {
    
    
    NSLog(@"%d",self.xuanzhong);
    
 
 
    
    if (!(self.textView.text.length > 0)) {
        
        [MBProgressHUD showError:@"请输入内容"];
        
        
               return ;
    }
    
   
    
    
       NSString *uid = [HWLocallyStoredData getLoginUserID];
    
    
         if ([uid isEqualToString:@""]) {
               [MBProgressHUD showError:@"请先登录"];
                return ;
         }
    
    
    
  NSString *userID = [HWLocallyStoredData getLoginUserID];
            NSString *tStr = [NSString stringWithFormat:@"%ld",[WMUtil getTimeSp]];
            NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];
            NSString *signMD5 = [WMUtil md5HexDigest:sign];
     
         // 659

          NSDictionary *parametes = @{
                                           @"ct" :  @"app",
                                           @"ac" : @"add_pinglun",
                                           @"ios" : @"1",
                                           @"t":tStr,
                                           @"uid":userID,
                                           @"sign":signMD5,
                                           @"id":self.idStr,
                                           @"content":self.textView.text,
                                           @"member_id":[HWLocallyStoredData getCode],
                                           
                                     
                                           };
               
               
             
               
               [HWWebUtils do3GetWithParameters:parametes progress:nil success:^(id response) {
                   
                   
                   NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
                  
                 
                   [MBProgressHUD hideHUD];
                   
                 
                   
                   
                   if ([codeStr intValue] == 1) {
                     //  [MBProgressHUD  showError:@"加载成功"];
                        //    NSArray *arr = response[@"data"];
                       
                         [self buttonTouxiangTap];
                       
                        [MBProgressHUD showError:response[@"message"]];
                       
                       

                     
                       
                       
                   } else {
                       
                     
                       
                   //      [MBProgressHUD showError:response[@"message"]];
                       
                        [MBProgressHUD showError:response[@"message"]];
                       
                      //  [self.maincollectionView reloadData];
                    
                       
                   }
                   NSLog(@"%@",response);
                   
                   
               } failure:^(NSString *error) {
                   
                  
                   
                   
               }];
   
    
    
}





@end
